import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from BlogAutoTest.common.Utils import BlogDriver


class BlogLogin:
    def __init__(self):
        self.url = "http://8.137.19.140:9090/blog_login.html"
        self.driver = BlogDriver.driver
        self.driver.get(self.url)
        self.wait = WebDriverWait(self.driver, 15)  # 全局显式等待（超时10秒）

    # 成功登录测试用例
    def LoginSucTest(self):
        try:
            # 输入用户名和密码
            self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#username"))).send_keys("zhangsan")
            self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#password"))).send_keys("123456")

            # 点击登录按钮
            self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#submit"))).click()

            # 验证登录成功（检查首页昵称）
            self.wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "body > div.container > div.left > div > h3"))
            )
            BlogDriver.getScreeShot()

            # 返回登录页面
            self.driver.back()
        except Exception as e:
            print("登录成功测试失败:", e)
            raise

    # 异常登录测试用例
    def LoginFailTest(self):
        test_cases = [
            {"username": "zhang", "password": "123456"},  # 错误账号
            {"username": "zhangsan", "password": "123"},  # 错误密码
            {"username": "zhangsan", "password": ""},  # 空密码
            {"username": "", "password": "123456"},  # 空账号
            {"username": "", "password": ""},  # 空账号和密码
        ]

        for case in test_cases:
            try:
                # 清空输入框
                self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#username"))).clear()
                self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#password"))).clear()

                # 输入测试数据
                if case["username"]:
                    self.driver.find_element(By.CSS_SELECTOR, "#username").send_keys(case["username"])
                if case["password"]:
                    self.driver.find_element(By.CSS_SELECTOR, "#password").send_keys(case["password"])

                # 提交登录
                self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#submit"))).click()

                # 显式等待弹窗出现
                self.wait.until(EC.alert_is_present())
                alert = self.driver.switch_to.alert
                print(f"测试用例 '{case}' 弹窗提示:", alert.text)
                alert.accept()

                # 最后一个用例截图
                if case == test_cases[-1]:
                    BlogDriver.getScreeShot()
            except Exception as e:
                print(f"测试用例 '{case}' 执行失败:", e)
                raise